import React, { PureComponent } from 'react'
import {
  AutoComplete,
  Button,
  Col,
  DatePicker,
  Form,
  Input,
  message,
  Popover,
  Radio,
  Row,
  Select,
  Spin,
  Switch,
  Tabs,
  Upload,
} from 'antd'
import { connect, history, withRouter } from '@umijs/max'
import _ from 'lodash'
import moment from 'moment'
import { regExp } from '@/utils/regExp.js'
import { getHashParameterByName } from '@/utils/helper'
import { CreateDiffEditor, ProTable } from '@/components'
import { getProjectId, SUAN_PAN } from '@/utils/https'
import styles from './index.less'

const { Item, List } = Form
const { TabPane } = Tabs
const { Option } = Select
const { Dragger } = Upload
const { Search } = Input
const modelStr = `function parseJson(inputParam) {
    // inputParam为返回报文的JSON字符串
    // var dataObj = JSON.parse(inputParam)
    // var result=[['参数1','参数2','...']]  // 定义参数名
    // var 参数1 = dataObj.errno //输入根节点数据
    // for(i=0; i < dataObj.xx.length; i++) {  // 此处输入处理逻辑,以循环遍历为例
    //    var arr = []
    //    var 参数2 = dataObj.xx[0].yy  // 输入叶子节点数据
    //    arr.push(参数1)
    //    arr.push(参数2)
    //    result.push(arr)
    // }
    // return result
  }`

const descRe = regExp.name(1, 32)
const lenRe = regExp.proName(1, 128)
const urlLenRe = regExp.proName(1, 8182)
const tokenLenRe = regExp.proName(1, 4096)

class DataSource extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      activeTabKey: '1',
      jsScript: modelStr,
      rawJson: '',
      apiLoading: false,
      fieldSuggestion: [],
      resExampleRawJson: '',
      tableViewLoading: false,
      previewSta: true,
      fileList: [],
      searchInputLoading: false,
      ports: [],
      serviceResSta: true, // 根据服务地址返回的值 控制端口、调用方法状态
      portOperationMap: {},
      selectedPort: '',
    }

    this.editorResonseId = `${Math.random()}`
    this.editorJsEditId = `${Math.random()}`
    this.editorObjectEditId = `${Math.random()}`

    this.dataSourceForm = React.createRef()
    // this.tableData = React.createRef()
    this.customEditorRef = React.createRef()
    this.objectParamsRef = React.createRef()
  }

  componentDidMount() {
    const id = getHashParameterByName('id')
    const isView = getHashParameterByName('isView')
    const { formData } = this.props || {}
    if (id && !formData?.isGoBack) {
      this.viewDetail(id, isView)
    } else {
      this.initParams()
    }
  }

  // 查看详情
  viewDetail = (idParams, isView) => {
    this.props.dispatch({
      type: 'webServiceApiCreate/queryGetTaskById',
      params: {
        id: idParams,
      },
      cb: (res) => {
        const {
          apiWsRequest, apiHttpRequest, previewExpressRequest, taskName, taskConfigRequest, id,
        } = res || {}
        const { fieldMappings } = taskConfigRequest || {}
        const relation = []
        fieldMappings?.map((item) => {
          relation.push({
            source: {
              fieldName: item.sourceField,
              fieldType: item.sourceFieldType,
              isPk: item.isSourceFieldPk,
              comment: item.comment,
              key: item.sourceField,
            },
            target: {
              fieldName: item.targetField,
              fieldType: item.targetFieldType,
              isPk: item.isTargetFieldPk,
              comment: item.comment,
              key: item.targetField,
            },
          })
          return null
        })

        this.props.dispatch({
          type: 'webServiceApiCreate/saveFormData',
          params: {
            formData: {
              id,
              previewExpressRequest,
              taskName,
              relation,
              isView: !!isView,
              apiWsRequest: apiWsRequest || apiHttpRequest, //  去掉 apiHttpRequest
              ...taskConfigRequest,
            },
          },
          cb: () => {
            this.initParams()
          },
        })
      },
    })
  }

  // 初始化页面参数
  initParams = () => {
    const { formData } = this.props
    const {
      apiWsRequest, taskName, previewExpressRequest,
    } = formData || {}

    console.log('dataSource formData', formData)
    const {
      address, addressPasswordKey, addressPasswordValue, addressUserNameKey, addressUserNameValue, localClassPath, operation, port, protocol, service, apiWsAuthParam, apiWsRequestBodyParam,
    } = apiWsRequest || {}
    const isLoginInfo = !!addressUserNameKey
    const { expressionParamList, jsScript, responseRawJson } = previewExpressRequest || {}
    const { body = '' } = apiWsRequestBodyParam || {}
    this.setState({
      rawJson: body,
    })

    // 认证类型为 自定义文件 的情况
    const {
      authType, advancedFileName, advancedCacheKey, expires,
    } = apiWsAuthParam || {}
    if (authType === 'jar') {
      const tempExpires = expires && moment(expires, 'YYYY-MM-DD')
      this.dataSourceForm.current.setFieldsValue({ expires: tempExpires })

      this.setState({
        fileList: [{
          uid: Math.random(),
          name: advancedFileName,
          status: 'done',
        }],
        advancedCacheKey,
      })
    }

    const ResultVariableName = []
    const parentVar = []
    expressionParamList?.map(item => {
      ResultVariableName.push({
        varName: item.name,
        varExpression: item.expression,
      })
      if (item.relationship === 0) {
        parentVar.push(item.name)
      }
      return null
    })

    this.setState({
      service,
      localClassPath,
      serviceResSta: !address,
      selectedPort: port || '',
      jsScript: jsScript || modelStr,
      resExampleRawJson: responseRawJson,
    })

    const fieldObj = {
      address,
      isLoginInfo,
      addressPasswordKey,
      addressPasswordValue,
      addressUserNameKey,
      addressUserNameValue,
      operation,
      port,
      protocol,
      // service,
      taskName,
      ResultVariableName: ResultVariableName?.length > 0 ? ResultVariableName : [{
        varName: undefined,
        varExpression: undefined,
      }],
      parentVar,
      tabSelectedVal: jsScript ? 'custom' : 'default',
      varRelationship: parentVar.length > 0 ? 'differentLevels' : 'sameLevel',
      ...apiWsAuthParam,
      ...apiWsRequestBodyParam,
    }
    delete fieldObj.expires
    this.dataSourceForm.current.setFieldsValue(fieldObj)

    const queryWsdlPortParams = {
      address,
      addressPasswordKey,
      addressPasswordValue,
      addressUserNameKey,
      addressUserNameValue,
    }

    const id = getHashParameterByName('id')
    const isView = getHashParameterByName('isView')
    // id && !isView && this.testData(true, body)
    setTimeout(() => {
      (id || formData?.isGoBack) && !isView && this.testData(true, body)
    })
    address && !isView && this.queryGetWsdlPortOperationMap(queryWsdlPortParams, true)
  }

  // 接口测试
  testData = (isInit = false, resBody = '') => {
    const {
      activeTabKey, advancedCacheKey, localClassPath, service, rawJson,
    } = this.state

    // isLoginInfo
    const { isLoginInfo } = this.dataSourceForm.current.getFieldsValue()
    const loginInfoCheckField = isLoginInfo ? ['addressPasswordKey', 'addressPasswordValue', 'addressUserNameKey', 'addressUserNameValue'] : []

    const checkFiled = ['taskName', 'protocol', 'address', 'port', 'operation', 'authType', 'accessKey', 'accessSecret', 'advancedFilePath', 'expires', 'bodyType', 'advanceClassReference', 'advanceMethodName', 'accessToken', ...loginInfoCheckField]

    const bodyRaw = this.objectParamsRef?.current?.getEditorValue() || ''

    this.dataSourceForm.current.validateFields(checkFiled).then(values => {
      const {
        authType, accessKey, accessSecret, accessToken, expires, bodyType, advanceClassReference, advanceMethodName, advancedFilePath, addressPasswordKey, addressPasswordValue, addressUserNameKey, addressUserNameValue, address, operation, port, protocol,
      } = values

      this.setState({
        apiLoading: true,
      })

      this.props.dispatch({
        type: 'webServiceApiCreate/queryTest',
        params: {
          addressPasswordKey,
          addressPasswordValue,
          addressUserNameKey,
          addressUserNameValue,
          address,
          operation,
          port,
          protocol,
          service,
          localClassPath,
          apiWsAuthParam: {
            authType,
            accessKey,
            accessSecret,
            accessToken,
            expires: expires && `${moment(expires).format('YYYY-MM-DD')} 23:59:59` || undefined,
            advanceClassReference,
            advanceMethodName,
            advancedFilePath,
            advancedCacheKey,
          },
          apiWsRequestBodyParam: {
            contentType: bodyType || 'application/json',
            body: bodyRaw || resBody || rawJson,
          },
        },
        cb: (res) => {
          const { data: resData, msg, status } = res || {}
          this.setState({
            apiLoading: false,
          })
          if (status === 200) {
            let resExampleRawJson
            try {
              resExampleRawJson = JSON.stringify(JSON.parse(resData?.responseBody))
              !isInit && message.success(msg || '请求成功')
            } catch (e) {
              message.error(resData?.responseBody)
              resExampleRawJson = ' '
            }
            this.setState({
              resExampleRawJson,
              fieldSuggestion: resData?.expressions || [],
            })
          } else {
            message.error(msg || '服务端错误')
          }
        },
      })
    }).catch(errorInfo => {
      // 提升用户体验，选中了认证必填项，但在其他tab页签，通过message.warn提示并切换tab页
      const {
        authType, advancedFilePath, accessKey, accessSecret, accessToken, advanceClassReference, advanceMethodName, expires,
      } = errorInfo?.values || {}
      if (activeTabKey !== '1' && authType !== 'noauth' && (!advancedFilePath || !accessKey || !accessSecret || !accessToken || !advanceClassReference || !advanceMethodName || !expires)) {
        message.warn('请完善必填项')
        this.setState({
          activeTabKey: '1',
        })
      }
    })

    return null
  }

  // 预览
  handlePreview = () => {
    const { resExampleRawJson, activeTabKey } = this.state
    const jsScript = this.customEditorRef?.current?.getEditorValue() || ''

    this.dataSourceForm.current.validateFields().then(values => {
      const {
        ResultVariableName, parentVar = [], tabSelectedVal,
      } = values

      const paramExpressionInfos = []
      if (tabSelectedVal === 'default') {
        ResultVariableName?.map((item) => {
          paramExpressionInfos.push({
            expression: item?.varExpression,
            name: item?.varName,
            relationship: parentVar?.indexOf(item?.varName) === -1 ? 1 : 0,
          })
          return null
        })
      }

      if ((jsScript === '' || jsScript === modelStr) && tabSelectedVal === 'custom') {
        message.warning('请输入自定义脚本')
        return null
      }

      this.setState({
        tableViewLoading: true,
      })

      this.props.dispatch({
        type: 'webServiceApiCreate/queryPreview',
        params: {
          responseRawJson: resExampleRawJson,
          expressionParamList: tabSelectedVal === 'default' ? paramExpressionInfos : [],
          jsScript: tabSelectedVal === 'custom' ? jsScript : '',
        },
        cb: (res) => {
          const { status, msg, data: dataRes = [] } = res || {}
          const tablePreviewColumn = []
          const tablePreview = []
          if (status === 200) {
            dataRes[0]
            && dataRes[0].map((item) => {
              tablePreviewColumn.push({
                title: item,
                dataIndex: item,
                key: item,
                width: 100,
                render: (txt) => (<div className={styles.td_ellipse} title={txt}>{txt}</div>),
              })
              return null
            })

            dataRes.slice(1).map((item) => {
              const obj = {}
              dataRes[0].map((val, key) => {
                obj[val] = `${item[key]}` // + ''  为了容错，后端返回的值为 对象类型
                return null
              })
              tablePreview.push(obj)
              return null
            })
            this.setState({
              tablePreview,
              tablePreviewColumn,
              tablePreviewColumnArray: dataRes[0],
              tableViewLoading: false,
              previewSta: false,
            })
          } else {
            message.warning(msg || '预览失败')
            this.setState({
              tableViewLoading: false,
              previewSta: true,
            })
          }
        },
      })
      return null
    }).catch(errorInfo => {
      const {
        authType, advancedFilePath, accessKey, accessSecret, accessToken, advanceClassReference, advanceMethodName, expires,
      } = errorInfo?.values || {}
      if (activeTabKey !== '1' && authType !== 'noauth' && (!advancedFilePath || !accessKey || !accessSecret || !accessToken || !advanceClassReference || !advanceMethodName || !expires)) {
        message.warn('请完善必填项')
        this.setState({
          activeTabKey: '1',
        })
      }
    })
  }

  // 下一步按钮回调
  nextStep = () => {
    const {
      tablePreviewColumnArray, advancedCacheKey, advancedFileName, resExampleRawJson, localClassPath, service, rawJson,
    } = this.state
    const jsScript = this.customEditorRef?.current?.getEditorValue() || ''

    this.dataSourceForm.current.validateFields().then(
      values => {
        const formData = { tablePreviewColumnArray }
        const {
          taskName, addressPasswordKey, addressPasswordValue, addressUserNameKey, addressUserNameValue, address, operation, port, protocol, authType, accessKey, accessSecret, accessToken, expires, bodyType, advanceClassReference, advanceMethodName, advancedFilePath, tabSelectedVal, ResultVariableName, parentVar = [],
        } = values

        if ((jsScript === '' || jsScript === modelStr) && tabSelectedVal === 'custom') {
          message.warning('请输入自定义脚本')
          return null
        }

        const bodyRaw = this.objectParamsRef?.current?.getEditorValue() || rawJson || ''

        const paramExpressionInfos = []
        if (tabSelectedVal === 'default') {
          ResultVariableName?.map((item, index) => {
            paramExpressionInfos.push({
              expression: item?.varExpression,
              name: item?.varName,
              relationship: parentVar?.indexOf(item?.varName) === -1 ? 1 : 0,
            })
            return null
          })
        }

        this.props.dispatch({
          type: 'webServiceApiCreate/saveFormData',
          params: {
            formData: {
              ...this.props.formData,
              ...formData,
              taskName,
              apiWsRequest: {
                addressPasswordKey,
                addressPasswordValue,
                addressUserNameKey,
                addressUserNameValue,
                address,
                operation,
                port,
                protocol,
                service,
                localClassPath,
                apiWsAuthParam: {
                  authType,
                  accessKey,
                  accessSecret,
                  accessToken,
                  expires: expires && `${moment(expires).format('YYYY-MM-DD')} 23:59:59` || null,
                  advanceClassReference,
                  advanceMethodName,
                  advancedFilePath,
                  advancedCacheKey,
                  advancedFileName, // 保存上传的jar文件名，用于返显
                },
                apiWsRequestBodyParam: {
                  contentType: bodyType || 'application/json',
                  body: bodyRaw,
                },
              },
              previewExpressRequest: {
                jsScript,
                expressionParamList: paramExpressionInfos,
                responseRawJson: resExampleRawJson,
              },
            },
          },
        })
        this.props.changeStep(1)
        return null
      },
      error => {
        const errorItem = error.errorFields[0]
        if (errorItem) {
          if ((errorItem.errors[0] === '请输入key' && errorItem.name[0] === 'accessKey')
            || (errorItem.errors[0] === '请输入value' && errorItem.name[0] === 'accessSecret')
            || (errorItem.errors[0] === '请输入Token' && errorItem.name[0] === 'accessToken')
            || (errorItem.errors[0] === '请上传jar包' && errorItem.name[0] === 'advancedFilePath')
            || (errorItem.errors[0] === '请输入类名' && errorItem.name[0] === 'advanceClassReference')
            || (errorItem.errors[0] === '请输入方法名' && errorItem.name[0] === 'advanceMethodName')
            || (errorItem.errors[0] === '请输入变量有效期' && errorItem.name[0] === 'expires')
          ) {
            message.warn('请完善必填项')
            this.setState({ activeTabKey: '1' })
          }
        }
      },
    )
  }

  disabledDate = current => current && current < moment().subtract(1, 'days')

  // eslint-disable-next-line react/sort-comp
  debounceSetText = _.debounce(async (e) => {
    const address = this.dataSourceForm.current.getFieldValue('address')
    const val = e?.type === 'click' ? address : e?.target.value
    const isLoginSwitch = this.dataSourceForm.current.getFieldValue('isLoginInfo')
    const validateFieldsArr = isLoginSwitch ? ['addressUserNameKey', 'addressUserNameValue', 'addressPasswordKey', 'addressPasswordValue'] : []

    this.dataSourceForm.current.validateFields(validateFieldsArr).then(values => {
      const {
        addressPasswordKey, addressPasswordValue, addressUserNameKey, addressUserNameValue,
      } = values
      const params = {
        address: val,
        addressPasswordKey,
        addressPasswordValue,
        addressUserNameKey,
        addressUserNameValue,
      }
      this.setState({
        searchInputLoading: true,
      })
      this.queryGetWsdlPortOperationMap(params)
    })
  }, 600);

  queryGetWsdlPortOperationMap = (params, isGoBack = false) => {
    this.props.dispatch({
      type: 'webServiceApiCreate/queryGetWsdlPortOperationMap',
      params,
      cb: (res) => {
        const {
          msg, status, data,
        } = res || {}
        const {
          portOperationMap, ports, service, localClassPath,
        } = data || {}

        !isGoBack && this.dataSourceForm.current.resetFields(['port', 'operation'])

        if (status === 200) {
          const setField = !isGoBack ? {
            service,
            localClassPath,
            serviceResSta: false,
            searchInputLoading: false,
            selectedPort: '',
          } : {}
          this.setState({
            portOperationMap,
            ports,
            ...setField,
          })
        } else {
          message.warning(msg || '服务端错误')
          const setField = !isGoBack ? {
            serviceResSta: true,
            service: '',
            searchInputLoading: false,
            selectedPort: '',
            localClassPath: '',
          } : {}
          this.setState({
            portOperationMap: {},
            ports: [],
            ...setField,
          })
        }
      },
    })
  }

  // 根据输入的服务地址，发送请求
  handleServiceAddress = (e) => {
    e.persist()
    this.debounceSetText(e)
  }

  // 选择端口
  handleSelectPort = (val) => {
    this.setState({
      selectedPort: val,
    })
  }

  render() {
    const { isView } = this.props.formData
    const {
      activeTabKey, jsScript, rawJson, apiLoading, fieldSuggestion, resExampleRawJson, tablePreviewColumn, tablePreview, previewSta, tableViewLoading, fileList, searchInputLoading, ports, serviceResSta, portOperationMap, selectedPort,
    } = this.state
    return (
      <div className={styles.data_source}>
        <Form
          ref={this.dataSourceForm}
          labelCol={{ span: 2 }}
          wrapperCol={{ span: 10 }}
          initialValues={this.props.initialValues}
          autoComplete="off"
        >
          <Item>
            <div className={styles.column}>基础设置</div>
          </Item>
          <Item
            label="任务名称"
            name="taskName"
            rules={[
              { required: true, message: '请输入任务名称' },
              {
                pattern: new RegExp(descRe.reg, 'g'),
                message: descRe.text,
              }]}
          >
            <Input placeholder="请输入任务名称" disabled={isView} />
          </Item>
          <Item>
            <div className={styles.column}>常量参数设置</div>
          </Item>
          <Item
            label="协议"
            name="protocol"
            rules={[{ required: true, message: '请选择协议' }]}
            initialValue="jax-ws"
          >
            <Radio.Group disabled={isView}>
              <Radio value="jax-ws">jax-ws</Radio>
              <Radio value="jax-rs">jax-rs</Radio>
            </Radio.Group>
          </Item>
          <Item
            label="填写登录信息"
            name="isLoginInfo"
            rules={[
              { required: true, message: '请填写登录信息' },
            ]}
            initialValue={false}
            valuePropName="checked"
          >
            <Switch disabled={isView} checkedChildren="是" unCheckedChildren="否" />
          </Item>
          <Item shouldUpdate noStyle>
            {
              (form) => form.getFieldValue('isLoginInfo') && (
                <>
                  <Item
                    label="用户名"
                    className={styles.required}
                    style={{ marginBottom: 0 }}
                  >
                    <Row>
                      <Col span={8}>
                        <Item
                          name="addressUserNameKey"
                          rules={[
                            { required: true, message: '请输入用户名key' },
                            {
                              pattern: new RegExp(lenRe.reg, 'g'),
                              message: lenRe.text,
                            },
                          ]}
                        >
                          <Input disabled={isView} type="text" autoComplete="off" placeholder="请输入用户名key" />
                        </Item>
                      </Col>
                      <Col span={1} />
                      <Col span={15}>
                        <Item
                          name="addressUserNameValue"
                          rules={[
                            { required: true, message: '请输入用户名value' },
                            {
                              pattern: new RegExp(lenRe.reg, 'g'),
                              message: lenRe.text,
                            },
                          ]}
                        >
                          <Input disabled={isView} type="text" autoComplete="off" placeholder="请输入用户名value" />
                        </Item>
                      </Col>
                    </Row>
                  </Item>
                  <Item
                    label="密码"
                    className={styles.required}
                    style={{ marginBottom: 0 }}
                  >
                    <Row>
                      <Col span={8}>
                        <Item
                          name="addressPasswordKey"
                          rules={[
                            { required: true, message: '请输入密码key' },
                            {
                              pattern: new RegExp(lenRe.reg, 'g'),
                              message: lenRe.text,
                            },
                          ]}
                        >
                          <Input disabled={isView} type="text" autoComplete="off" placeholder="请输入密码key" />
                        </Item>
                      </Col>
                      <Col span={1} />
                      <Col span={15}>
                        <Item
                          name="addressPasswordValue"
                          rules={[
                            { required: true, message: '请输入密码value' },
                            {
                              pattern: new RegExp(lenRe.reg, 'g'),
                              message: lenRe.text,
                            },
                          ]}
                        >
                          <Input disabled={isView} type="text" autoComplete="off" placeholder="请输入密码value" />
                        </Item>
                      </Col>
                    </Row>
                  </Item>
                </>
              )
            }
          </Item>
          <Item
            label="服务地址"
            name="address"
            rules={[
              { required: true, message: '请输入服务地址' },
              {
                pattern: new RegExp(urlLenRe.reg, 'g'),
                message: urlLenRe.text,
              },
            ]}
          >
            <Search
              loading={searchInputLoading}
              onChange={this.handleServiceAddress}
              onPressEnter={this.handleServiceAddress}
              onSearch={(val, e) => { this.handleServiceAddress(e) }}
              disabled={isView}
              type="text"
              autoComplete="off"
              placeholder="请输入服务地址"
            />
          </Item>
          <Item
            label="端口"
            name="port"
            rules={[{ required: true, message: '请选择端口' }]}
          >
            <Select onSelect={this.handleSelectPort} disabled={isView || serviceResSta} placeholder="请选择端口">
              {
                ports?.map(item => (
                  <Option label={item} key={item} value={item}>
                    {item}
                  </Option>
                ))
              }
            </Select>
          </Item>
          <Item
            label="调用方法"
            name="operation"
            rules={[{ required: true, message: '请选择调用方法' }]}
          >
            <Select placeholder="请选择调用方法" disabled={isView || selectedPort === ''}>
              {
                portOperationMap?.[selectedPort]?.map(item => (
                  <Option key={item} value={item}>
                    {item}
                  </Option>
                ))
              }
            </Select>
          </Item>
          <Item wrapperCol={{ span: 12 }}>
            <Tabs
              defaultActiveKey="1"
              activeKey={activeTabKey}
              onChange={(e) => { this.setState({ activeTabKey: e }) }}
            >
              <TabPane tab="认证" key="1">
                <Item
                  labelCol={{ span: 4 }}
                  wrapperCol={{ span: 20 }}
                  label="类型"
                  name="authType"
                  rules={[{ required: true, message: '请选择认证类型' }]}
                  initialValue="noauth"
                >
                  <Select
                    disabled={isView}
                    placeholder="请选择认证类型"
                  >
                    <Option value="noauth">无</Option>
                    <Option value="sign">API密钥</Option>
                    <Option value="token">Token令牌</Option>
                    <Option value="jar">自定义认证</Option>
                  </Select>
                </Item>
                <Item shouldUpdate noStyle>
                  {(form) => form.getFieldValue('authType') === 'sign' && (
                    <>
                      <Item
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        label="key"
                        name="accessKey"
                        rules={[
                          { required: true, message: '请输入key' },
                          {
                            pattern: new RegExp(lenRe.reg, 'g'),
                            message: lenRe.text,
                          },
                        ]}
                      >
                        <Input disabled={isView} placeholder="请输入key" />
                      </Item>
                      <Item
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        label="value"
                        name="accessSecret"
                        rules={[
                          { required: true, message: '请输入value' },
                          {
                            pattern: new RegExp(lenRe.reg, 'g'),
                            message: lenRe.text,
                          },
                        ]}
                      >
                        <Input disabled={isView} placeholder="请输入value" />
                      </Item>
                    </>
                  )}
                </Item>
                <Item shouldUpdate noStyle>
                  {(form) => form.getFieldValue('authType') === 'token' && (
                    <Item
                      labelCol={{ span: 4 }}
                      wrapperCol={{ span: 20 }}
                      label="Token"
                      name="accessToken"
                      rules={[
                        { required: true, message: '请输入Token' },
                        {
                          pattern: new RegExp(tokenLenRe.reg, 'g'),
                          message: tokenLenRe.text,
                        },
                      ]}
                    >
                      <Input disabled={isView} placeholder="请输入Token" />
                    </Item>
                  )}
                </Item>
                <Item shouldUpdate noStyle>
                  {(form) => form.getFieldValue('authType') === 'jar' && (
                    <>
                      <Item
                        wrapperCol={{ span: 24 }}
                        name="advancedFilePath"
                        rules={[{ required: true, message: '请上传jar包' }]}
                      >
                        <Dragger
                          disabled={isView}
                          name="file"
                          accept=".jar"
                          maxCount={1}
                          action={`${SUAN_PAN}/api/v1/integration/api/ws/uploadJar`}
                          headers={{ 'X-Project-Id': getProjectId() }}
                          fileList={fileList}
                          onChange={(info) => {
                            if (info.file.status !== 'uploading') {
                              // console.log(info.file, info.fileList);
                            }
                            if (info.file.status === 'done') {
                              const res = info.file.response
                              if (res.status === 200) {
                                message.success(`${info.file.name} 上传成功`)
                                this.dataSourceForm?.current?.setFieldsValue({ advancedFilePath: info?.file?.response?.data?.filePath })
                                const advancedCacheKey = info?.file?.response?.data?.cacheKey
                                const advancedFileName = info?.file?.name || ''
                                this.setState({
                                  advancedCacheKey,
                                  advancedFileName,
                                })
                              } else {
                                message.warning(res.msg, 3)
                                info.file.status = 'error'
                                info.file.response = res.msg || '上传错误'
                                info.fileList.find((item) => item.uid === info.file.uid).status = 'error'
                              }
                            } else if (info.file.status === 'error') {
                              message.error(`${info.file.name} 上传失败.`)
                            }
                            if (info.file.status === 'removed') {
                              this.dataSourceForm?.current?.setFieldsValue({ advancedFilePath: '' })
                            }

                            this.setState({
                              fileList: info?.fileList || [],
                            })
                          }}
                          onRemove={() => {
                            this.dataSourceForm?.current?.setFieldsValue({ advancedFilePath: '' })
                          }}
                          style={{ height: '200px' }}
                        >
                          <p className="ant-upload-drag-icon">
                            <i className="iconfont icon-cunchu" />
                          </p>
                          <p className="ant-upload-text">将文件拖拽至此，或单击直接上传</p>
                          <p className="ant-upload-hint">支持扩展名：jar</p>
                        </Dragger>
                      </Item>
                      <Item
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        label="类名"
                        name="advanceClassReference"
                        rules={[
                          { required: true, message: '请输入类名' },
                          {
                            pattern: new RegExp(lenRe.reg, 'g'),
                            message: lenRe.text,
                          },
                        ]}
                      >
                        <Input disabled={isView} placeholder="请输入类名" />
                      </Item>
                      <Item
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        label="方法名"
                        name="advanceMethodName"
                        rules={[
                          { required: true, message: '请输入方法名' },
                          {
                            pattern: new RegExp(lenRe.reg, 'g'),
                            message: lenRe.text,
                          },
                        ]}
                      >
                        <Input disabled={isView} placeholder="请输入方法名" />
                      </Item>
                      <Item
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        label="变量有效期"
                        name="expires"
                        rules={[{ required: true, message: '请输入变量有效期' }]}
                      >
                        <DatePicker
                          disabled={isView}
                          disabledDate={this.disabledDate}
                          // value={beginDay && moment(beginDay, 'YYYY-MM-DD')}
                          // onChange={this.handleBeginDay}
                          placeholder="请输入变量有效期"
                          style={{ width: '100%' }}
                        />
                      </Item>
                    </>
                  )}
                </Item>
              </TabPane>
              <TabPane tab="请求参数" key="2">
                <Item
                  label="类型"
                  name="bodyType"
                  rules={[{ required: true, message: '请选择请求体类型' }]}
                  initialValue="application/json"
                >
                  <Select disabled={isView}>
                    <Option key="application/json" value="application/json">application/json</Option>
                    {/* <Option key="single" value="single">单值</Option> */}
                  </Select>
                </Item>
                <Item shouldUpdate noStyle>
                  {(form) => form.getFieldValue('bodyType') === 'application/json' && (
                    <div className={styles.json_diff_editor}>
                      <CreateDiffEditor
                        readOnly={isView}
                        restData={rawJson || ''}
                        ref={this.objectParamsRef}
                        language="json"
                        theme="vs"
                        editorId={this.editorObjectEditId}
                      />
                    </div>
                  )}
                </Item>
              </TabPane>
            </Tabs>
          </Item>
          <Item wrapperCol={{ span: 12 }}>
            <Button
              disabled={isView}
              type="primary"
              loading={apiLoading}
              onClick={() => { this.testData() }}
            >
              接口测试
            </Button>
          </Item>
          <Item>
            <div className={styles.column}>返回示例</div>
          </Item>
          <Row gutter={16}>
            <Col span={12}>
              <Spin spinning={apiLoading}>
                <div className={`${styles.api_bottom_out_example} ${styles.api_bottom_out_example_left}`}>
                  <CreateDiffEditor
                    restData={resExampleRawJson || ''}
                    language="json"
                    readOnly
                    theme="vs"
                    editorId={this.editorResonseId}
                  />
                </div>
              </Spin>
            </Col>
            <Col span={12}>
              <Item
                noStyle
                name="tabSelectedVal"
                valuePropName="activeKey"
                initialValue="default"
              >
                <Tabs
                  destroyInactiveTabPane
                >
                  <TabPane tab="默认" key="default" className={styles.tab_pane_height}>
                    <List
                      name="ResultVariableName"
                      initialValue={[{
                        varName: undefined,
                        varExpression: undefined,
                      }]}
                    >
                      {(fields, { add, remove }) => fields.map(({ key, name, ...restField }, index) => (
                        <Item
                          labelCol={index === 0 ? { span: 5 } : { span: 0 }}
                          wrapperCol={index === 0 ? { span: 19 } : { span: 19, offset: 5 }}
                          label={index === 0 ? (
                            <span>
                              结果变量名
                              <Popover
                                content={
                                  <span>
                                    点击
                                    <span
                                      style={{ color: '#0084FF', cursor: 'pointer' }}
                                      onClick={() => {
                                        window.open(`${window.suanpan}Json.html`)
                                      }}
                                    >
                                      {' '}这里{' '}
                                    </span>
                                    查看Json解析说明
                                  </span>
                                }
                              >
                                <i className="iconfont icon-yiwentishi" />
                              </Popover>
                            </span>
                          ) : ''}
                          required
                          key={key}
                        >
                          <div className={styles.parameter_item}>
                            <Item
                              name={[name, 'varName']}
                              noStyle
                              rules={[
                                { required: true, message: '请输入结果变量名' },
                                {
                                  pattern: new RegExp(lenRe.reg, 'g'),
                                  message: lenRe.text,
                                },
                              ]}
                              style={{ display: 'inline-block', width: 'calc(50% - 8px)' }}
                            >
                              <Input disabled={isView} placeholder="请输入结果变量名" />
                            </Item>
                            <span className={styles.equal_sign}> = </span>
                            <Item
                              name={[name, 'varExpression']}
                              noStyle
                              rules={[
                                { required: true, message: '请输入结果表达式' },
                                {
                                  pattern: new RegExp(lenRe.reg, 'g'),
                                  message: lenRe.text,
                                },
                              ]}
                              style={{ display: 'inline-block', width: 'calc(50% - 8px)' }}
                            >
                              <AutoComplete
                                disabled={isView}
                                type="text"
                                autoComplete="off"
                                placeholder="请输入结果表达式"
                              >
                                {
                                  fieldSuggestion.map(item => (
                                    <Option key={item} value={item}>
                                      {item}
                                    </Option>
                                  ))
                                }
                              </AutoComplete>
                            </Item>
                            <div className={styles.item_btn_wrap}>
                              {
                                fields.length - 1 === index && <i className={`iconfont icon-tianjia1 ${styles.add_sign} ${isView ? styles.disabled : ''}`} onClick={() => add()} />
                              }
                              {
                                fields.length - 1 !== 0 && <i className={`iconfont icon-shanchu ${styles.del_sign} ${isView ? styles.disabled : ''}`} onClick={() => remove(name)} />
                              }
                            </div>
                          </div>
                        </Item>
                      ))}
                    </List>
                    <Item
                      labelCol={{ span: 5 }}
                      wrapperCol={{ span: 19 }}
                      label={
                        (
                          <span>
                            变量关系
                            <Popover
                              content="通过设置变量的层级关系，将有层级的json数据平展为数据库表，仅支持2种层级关系"
                            >
                              <i className="iconfont icon-yiwentishi" />
                            </Popover>
                          </span>
                        )
                      }
                      name="varRelationship"
                      rules={[{ required: true, message: '请选择变量关系' }]}
                      initialValue="sameLevel"
                    >
                      <Select disabled={isView}>
                        <Option key="sameLevel" value="sameLevel">
                          同级别
                        </Option>
                        <Option key="differentLevels" value="differentLevels">
                          不同级别
                        </Option>
                      </Select>
                    </Item>
                    <Item
                      noStyle
                      shouldUpdate
                    >
                      {(form) => {
                        const parentVarList = []
                        form.getFieldValue('ResultVariableName').map((item) => {
                          if (item && item.varName) {
                            parentVarList.push(item.varName)
                          }
                        })
                        return form.getFieldValue('varRelationship') === 'differentLevels' && (
                        <Item
                          name="parentVar"
                          wrapperCol={{ span: 20, offset: 5 }}
                          label=""
                          rules={[{ required: true, message: '请选择父级的变量' }]}
                        >
                          <Select
                            disabled={isView}
                            mode="multiple"
                            maxTagCount={4}
                            maxTagTextLength={7}
                            placeholder="请选择父级的变量"
                          >
                            {
                              parentVarList.map(item => (
                                <Option key={item} value={item}>
                                  {item}
                                </Option>
                              ))
                            }
                          </Select>
                        </Item>
                        )
                      }}
                    </Item>
                  </TabPane>
                  <TabPane tab="自定义" key="custom" className={styles.tab_pane_height}>
                    <div className={`${styles.api_bottom_out_example} ${styles.api_bottom_out_example_custom}`}>
                      <CreateDiffEditor
                        readOnly={isView}
                        language="javascript"
                        theme="vs"
                        editorId={this.editorJsEditId}
                        ref={this.customEditorRef}
                        restData={jsScript || ''}
                      />
                    </div>
                  </TabPane>
                </Tabs>
              </Item>
              <Item
                className={styles.btn_wrap}
                wrapperCol={{ span: 20, offset: 5 }}
                label=""
                colon={false}
                name="varRelationship"
              >
                <Button type="primary" loading={tableViewLoading} onClick={this.handlePreview}>预览</Button>
              </Item>
              <Item
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 19 }}
                label="计算结果"
              >
                <ProTable
                  loading={tableViewLoading}
                  rowKey={() => (Math.random())}
                  columns={tablePreviewColumn}
                  dataSource={tablePreview}
                  scroll={{ x: true, y: 110 }}
                  pagination={false}
                />
              </Item>
            </Col>
          </Row>
        </Form>
        <div className={styles.edit_footer}>
          <Button
            className={styles.edit_btn}
            onClick={() => { history.push('/dataIntegrate/apiGather/webService') }}
          >
            取消
          </Button>
          <Button
            className={styles.edit_btn}
            type="primary"
            onClick={this.nextStep}
            disabled={previewSta}
          >
            下一步
          </Button>
        </div>
      </div>
    )
  }
}

// export default DataSource
export default connect(({ webServiceApiCreate }) => ({ ...webServiceApiCreate }))(withRouter(DataSource))
